/**
 * AI服务
 * 处理AI聊天、模型管理、知识库等相关功能
 */
import { BaseService } from './base-service'
import type { ApiResponse } from '../../../types/api'

// AI模型信息
export interface AIModel {
  id: number
  vendor: string
  icon?: string
  name: string
  apiKey?: string
  apiUrl?: string
  tags?: string
  type: string
  status: number
  description?: string
  params?: string
  createTime?: string
  updateTime?: string
}

// 对话请求参数
export interface ChatParams {
  message: string
  sessionId?: string
  modelId?: number  // 使用modelId而不是model，类型改为number与后端保持一致
  temperature?: number
  maxTokens?: number
}

// 知识库信息
export interface KnowledgeBase {
  id: string
  name: string
  description?: string
  documentCount?: number
  createdAt?: string
}

// 知识库文档
export interface KnowledgeDocument {
  id: string
  name: string
  type: string
  size: number
  status: string
  processedAt?: string
}

export class AiService extends BaseService {
  constructor() {
    super()
  }

  /**
   * 获取AI流式对话URL（带记忆）
   */
  getStreamApiUrlWithMemory(sessionId: string, message: string, systemPromptId?: number | null): string {
    let url = `/chat/ai/generateStreamWithMemory?sessionId=${encodeURIComponent(sessionId)}&message=${encodeURIComponent(message)}`
    if (systemPromptId !== undefined && systemPromptId !== null) {
      url += `&systemPromptId=${encodeURIComponent(systemPromptId.toString())}`
    }
    return url
  }

  /**
   * 获取AI流式对话URL（带记忆，指定模型）
   */
  getStreamApiUrlWithMemoryByModel(sessionId: string, message: string, modelId: number): string {
    return `/chat-test/ai/generateStreamWithMemoryByModel?sessionId=${encodeURIComponent(sessionId)}&message=${encodeURIComponent(message)}&modelId=${encodeURIComponent(modelId.toString())}`
  }

  /**
   * 获取AI流式对话URL（不带记忆）
   */
  getStreamApiUrl(message: string): string {
    return `/chat/ai/generateStream?message=${encodeURIComponent(message)}`
  }

  /**
   * 流式聊天方法 - 统一入口点
   * @param params 聊天参数
   * @param callbacks 回调函数集合
   */
  async streamChat(params: {
    userId?: number;
    sessionId?: string;
    content: string;
    modelId?: number;
    temperature?: number;
    maxTokens?: number;
    topP?: number;
    memory?: boolean;
    knowledgeId?: number;
    useTools?: boolean;
    contentIndex?: number; // 添加contentIndex参数
    systemPromptId?: number | null;
  }, callbacks: {
    onMessage: (data: { event: string; data: string }) => void;
    onError: (error: Error) => void;
    onComplete: () => void;
  }): Promise<void> {
    try {
      // 直接构建符合后端 QuestionVO 的请求体
      const requestBody = {
        message: params.content,
        sessionId: params.sessionId,
        modelId: params.modelId, // 保持为number类型，与后端保持一致
        memory: params.memory !== undefined ? params.memory : true,
        knowledgeId: params.knowledgeId,
        useTools: params.useTools || false,
        userId: params.userId || 0,
        contentIndex: params.contentIndex, // 添加contentIndex
        systemPromptId: params.systemPromptId
      };
      
      // 构建请求头
      const headers: Record<string, string> = {
        'Content-Type': 'application/json',
        'Accept': 'text/plain;charset=UTF-8'
      }
      
      // 添加Authorization头
      const token = await import('./api-config').then(m => m.ApiConfig.getToken());
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }
      
      // 使用fetch API调用流式接口
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/chat/generateStream`, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(requestBody)
      });
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      // 获取流式响应
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      
      // 累积内容
      let accumulatedContent = '';
      
      if (reader) {
        let done = false;
        while (!done) {
          const { value, done: readerDone } = await reader.read();
          done = readerDone;
          
          if (value) {
            const chunk = decoder.decode(value, { stream: true });
            
            // 累积内容
            accumulatedContent += chunk;
            
            // 触发消息回调，发送累积的完整内容
            callbacks.onMessage({
              event: 'message',
              data: accumulatedContent
            });
          }
        }
      }
      
      // 流结束，触发完成回调
      callbacks.onComplete();
    } catch (error) {
      console.error('流式聊天失败:', error);
      callbacks.onError(error as Error);
      throw error;
    }
  }

  /**
   * 获取视觉流式响应URL
   */
  getVisionStreamUrl(): string {
    return `${import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8080'}/vision/stream`
  }

  /**
   * 发送视觉消息
   */
  async sendVisionMessage(imageData: string, prompt: string): Promise<ApiResponse<any>> {
    const formData = new FormData()
    formData.append('image', imageData)
    formData.append('prompt', prompt)

    return this.post('/vision', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 10000
    })
  }

  /**
   * 获取AI模型列表
   */
  async getAiModels(filterParams?: any): Promise<ApiResponse<AIModel[]>> {
    const params = filterParams || {}
    return this.get<AIModel[]>('/aiModel/list', params)
  }

  /**
   * 删除AI模型
   */
  async deleteAiModel(id: string): Promise<ApiResponse<any>> {
    return this.post('/aiModel/delete', `id=${encodeURIComponent(id)}`, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
  }

  /**
   * 保存AI模型
   */
  async saveAiModel(modelData: any): Promise<ApiResponse<any>> {
    return this.post('/aiModel/save', modelData)
  }

  /**
   * 获取可用的模型图标列表
   */
  async getAvailableIcons(): Promise<ApiResponse<any>> {
    return this.get('/aiModel/icons')
  }

  /**
   * 上传模型图标
   */
  async uploadModelIcon(file: File): Promise<ApiResponse<any>> {
    const formData = new FormData()
    formData.append('file', file)
    
    return this.post('/aiModel/uploadIcon', formData)
  }

  /**
   * 清除指定sessionId的会话历史消息
   */
  async clearSessionHistory(sessionId: string): Promise<ApiResponse<any>> {
    return this.post('/memory/clearSession', new URLSearchParams({ sessionId }), {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    })
  }

  /**
   * 清除指定sessionId的会话历史记录（后端/sessionHistory/clear/{sessionId}接口）
   */
  async clearSessionHistoryFromBackend(sessionId: string): Promise<ApiResponse<any>> {
    return this.post(`/sessionHistory/clear/${sessionId}`)
  }

  /**
   * 获取用户历史会话列表
   */
  async getSessionHistoryList(): Promise<ApiResponse<any[]>> {
    const response = await this.get('/sessionHistory/list')
    
    // 处理API返回的数据结构
    if (response.code === 0 && response.data) {
      // 注意：API返回的结构可能是 {data: {data: [...]}}
      const data = response.data.data || response.data
      return {
        ...response,
        data: Array.isArray(data) ? data : []
      }
    }
    
    return response
  }

  /**
   * 创建会话
   */
  async createSession(sessionData: { sessionId: string; title: string; userId: number }): Promise<ApiResponse<any>> {
    return this.post('/sessionHistory/create', sessionData)
  }

  /**
   * 更新会话
   */
  async updateSession(sessionData: { sessionId: string; title: string }): Promise<ApiResponse<any>> {
    return this.post('/sessionHistory/update', sessionData)
  }

  /**
   * 获取会话详情
   */
  async getSessionDetail(sessionId: string): Promise<ApiResponse<any>> {
    return this.get('/sessionHistory/get', { sessionId })
  }

  /**
   * 删除会话（兼容方法，与deleteSessionHistory功能相同）
   */
  async deleteSession(id: string | number): Promise<ApiResponse<any>> {
    return this.deleteSessionHistory(id.toString())
  }

  /**
   * 删除会话历史记录
   */
  async deleteSessionHistory(sessionId: string): Promise<ApiResponse<any>> {   
    return this.delete(`/sessionHistory/${sessionId}`)
  }

  /**
   * 删除用户所有会话历史记录
   */
  async deleteAllSessionHistories(): Promise<ApiResponse<any>> {
    return this.delete('/sessionHistory/user/all')
  }

  /**
   * 向量检索
   */
  async vectorQuery(query: string, knowledgeId: string, threshold: number): Promise<ApiResponse<any>> {
    return this.get('/vector/query', { query, knowledgeId, threshold })
  }

  /**
   * 获取知识库列表
   */
  async getAllKnowledgeBases(): Promise<ApiResponse<KnowledgeBase[]>> {
    const response = await this.get('/knowledge-base/list')
    
    if (response.code === 0 && response.data) {
      return {
        ...response,
        data: response.data.data || response.data
      }
    }
    
    return response
  }

  /**
   * 获取启用的知识库列表
   */
  async getEnabledKnowledgeBases(): Promise<ApiResponse<KnowledgeBase[]>> {
    const response = await this.get('/knowledge-base/list?status=1')
    
    if (response.code === 0 && response.data) {
      return {
        ...response,
        data: response.data.data || response.data
      }
    }
    
    return response
  }

  /**
   * 获取提示词模板列表
   */
  async getPromptTemplates(): Promise<ApiResponse<any[]>> {
    const response = await this.get('/prompt/templates')
    
    if (response.code === 0 && response.data) {
      return {
        ...response,
        data: response.data.data || response.data
      }
    }
    
    return response
  }

  /**
   * 增加提示词模板使用次数
   */
  async incrementTemplateUsage(templateId: string): Promise<ApiResponse<any>> {
    return this.post(`/prompt/templates/${templateId}/increment-usage`)
  }

  /**
   * 根据ID获取知识库详情
   */
  async getKnowledgeBaseById(kbId: string): Promise<ApiResponse<KnowledgeBase>> {
    return this.get(`/knowledge-base/${kbId}`)
  }

  /**
   * 创建知识库
   */
  async createKnowledgeBase(kb: KnowledgeBase): Promise<ApiResponse<any>> {
    return this.post('/knowledge-base/create', kb)
  }

  /**
   * 更新知识库
   */
  async updateKnowledgeBase(kbId: string, kb: KnowledgeBase): Promise<ApiResponse<any>> {
    return this.put(`/knowledge-base/${kbId}`, kb)
  }

  /**
   * 删除知识库
   */
  async deleteKnowledgeBase(kbId: string): Promise<ApiResponse<any>> {
    return this.delete(`/knowledge-base/${kbId}`)
  }

  /**
   * 获取知识库文档列表
   */
  async getKnowledgeDocuments(knowledgeId: string, page: number = 1, size: number = 10): Promise<ApiResponse<any>> {
    return this.get('/document', { 
      knowledgeBaseId: knowledgeId, 
      page, 
      size 
    })
  }

  /**
   * 上传文件到知识库
   */
  async uploadFileToKnowledgeBase(knowledgeId: string, uploaderId: string, file: File): Promise<ApiResponse<any>> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('knowledgeBaseId', knowledgeId)
    formData.append('uploaderId', uploaderId)
    
    return this.post('/files/upload-to-knowledge-base', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }

  /**
   * 通过文件创建知识库文档
   */
  async createDocumentFromFile(document: any): Promise<ApiResponse<any>> {
    return this.post('/document/create-from-file', document)
  }

  /**
   * 添加文本文档到知识库
   */
  async addTextDocumentToKnowledgeBase(document: any): Promise<ApiResponse<any>> {
    return this.post('/document/add', document)
  }

  /**
   * 异步上传知识库文档
   */
  async uploadKnowledgeDocumentAsync(knowledgeId: string, _uploaderId: string, file: File): Promise<ApiResponse<any>> {
    const formData = new FormData()
    formData.append('file', file)
    formData.append('knowledgeBaseId', knowledgeId)
    
    return this.post('/files/upload-to-knowledge-base', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }

  /**
   * 获取知识库文档处理进度
   */
  async getKnowledgeDocumentProgress(docId: string): Promise<ApiResponse<any>> {
    return this.get(`/knowledge/document/progress/${docId}`)
  }

  /**
   * 删除文档
   */
  async deleteDocument(docId: string): Promise<ApiResponse<any>> {
    return this.delete(`/document/${docId}`)
  }

  /**
   * 获取文档详情
   */
  async getDocumentById(docId: string): Promise<ApiResponse<any>> {
    return this.get(`/document/${docId}`)
  }

  /**
   * 更新文档
   */
  async updateDocument(docId: string, docData: any): Promise<ApiResponse<any>> {
    return this.put(`/document/${docId}`, docData)
  }
}

// 创建单例实例
export const aiService = new AiService()

export default AiService